<template>
    <view class="wrap">
        <view class="addImg">
            <image @tap="uploadImg" :src="form.avatar" mode="aspectFill" lazy-load="false" />
            <view class="avatar">上传头像</view>
        </view>
        <view class="iptSyl">
            <van-field
                input-align="right"
                :value="form.nickName"
                placeholder="请输入昵称(最多输入6个字)"
                label="昵称"
                @change="getNickname"
            />
            <van-cell title="性别">
                <view class="sexWrap" >
                    <view class="sex" @tap="changeSex('1')" :style="{border: form.sex == 1 ? '1px solid #FF7F22' : none, color: form.sex == 1 ? '#FF7F22':'#000'}">男</view>
                    <view class="sex" @tap="changeSex('2')" :style="{border: form.sex == 2 ? '1px solid #FF7F22' : none, color: form.sex == 2 ? '#FF7F22':'#000'}">女</view>
                </view>
            </van-cell>
            <van-cell title="出生时间" is-link :value="form.birthdayNew" @tap="openChooseBirth('news')"/>
            <van-cell title="出生地点" is-link :value="form.birthAddr" @tap="openChooseAddr('oldAddr')"/>
			<view class="btn"><van-button  style="width: 690rpx;" color="#FF7F22" size="small" @tap="saveData">保存</van-button></view>

            <!-- 出生时间选择 -->
            <van-popup
                :show="birthdayNewShow"
                round
                closeable
                position="bottom"
                custom-style="height: 660rpx"
                @close="onClose"
            >
                <view class="title">{{ type == 'news' ? '出生时间(农历)':'出生时间(阳历)'}}</view>
                <view class="show">
                    <view>年</view>
                    <view>月</view>
                    <view>日</view>
                    <view>时</view>
                    <view>分</view>
                </view>
                <view class="boxWrap">
                    <van-datetime-picker
                        style="margin-top: 40rpx;"
                        :show-toolbar="disabledToolbar"
                        type="datetime"
                        :value="currentDate"
                        :min-date="minDate"
                        :max-date="maxDate"
                        @input="onInput"
                    />
                </view>
                
                <view class="saveBtn" style="padding: 30rpx" @tap="getTimer">
                    <van-button type="primary" block color="#FF7F22">完成</van-button>
                </view>
            </van-popup>
            <!-- 出生地点选择 -->
            <van-popup
                :show="addrShow"
                round
                closeable
                position="bottom"
                custom-style="height: 660rpx"
                @close="onClose"
            >
                <view class="title">{{ addrType == 'oldAddr' ? '出生地点':'现居城市'}}</view>
                <view style="height: 400rpx; overflow:hidden;">
                    <van-area :show-toolbar="disabledToolbar" :area-list="areaList" @change="getAddr" />
                </view>       
                <view class="saveBtn" style="padding: 30rpx" @tap="saveAddr">
                    <van-button type="primary" block color="#FF7F22">完成</van-button>
                </view>
            </van-popup>
            <van-toast id="van-toast" />
        </view>
    </view>
</template>
<script>
import moment from 'moment';
import { areaList } from '@vant/area-data';
import Toast from '../../../wxcomponents/@vant/weapp/toast/toast'
import { baseURL } from '../../../utils/baseUrl';
import {imgBaseUrl} from '../../../utils/baseUrl.js'
import { addRecordAPI } from '../../../utils/api';
import { Solar, Lunar, HolidayUtil } from 'lunar-javascript';
export default {
    data(){
        return {
            minHour: 10,
            maxHour: 20,
            minDate: new Date(1970).getTime(),
            maxDate: new Date().getTime(),
            currentDate: new Date().getTime(),
            birthdayNewShow: false, // 出生日期是否打开弹框
            addrShow:false,// 地址是否打开弹框
            disabledToolbar: false, // 禁用Toolbar
            type:'news', // news出生时间公历 old出生时间农历 
            addrType:'oldAddr', // oldAddr出生地  newAddr现居住地
            currentTime:'', // 临时存储选中时间
            currentAddr:'', // 临时存储地点
            areaList,
            relationArr:[],
            form:{
                avatar:imgBaseUrl + '/img/allImgs/record/addImg.svg',
                upAvatar:'',
                nickName:'',
                relation:'请选择',
                sex:0,
                birthdayNew:'',
                birthdayOld:'',
                birthAddr:'',
                nowAddr:''
            },
           
        }
    },
    methods:{
       
        // 保存数据
        async saveData(){
            const params = {
                currentAddress: this.form.birthAddr,
                birthPlace:this.form.birthAddr,
                birthday: this.form.birthdayNew == '' || this.form.birthdayNew ==  undefined ? '' :this.form.birthdayNew + ':00',
                lunarBirthday:this.form.birthdayOld,
                avatar: this.form.upAvatar,
                realname: this.form.nickName,
                sex: this.form.sex,
                relationship: "本人"
            }
            try {
                const res = await addRecordAPI(params); 
                if(res.code == 200){
                    Toast.success('添加成功');
					uni.setStorageSync('userInfo',res.result)
                    setTimeout(() => {
                        uni.reLaunch({
							url:'/pages/tabbar/home/home'
						})
                    }, 2000);
                }
            } catch (error) {
                
            }
        },  


        // 给出生时间赋值
        getTimer(){
            if(this.type == 'news'){
                this.form.birthdayNew = moment(this.currentTime).format("YYYY-MM-DD HH:mm");
                const lunarDate = Lunar.fromDate(new Date(this.currentTime));
                const time = lunarDate.getTimeInGanZhi();
                this.form.birthdayOld = String(lunarDate)+time
            }
            this.birthdayNewShow = false;
        },

        // 弹出地点弹出框
        openChooseAddr(type){
            this.addrType = type
            this.addrShow = true
        },

        // 存储地点
        saveAddr(){
            if(this.addrType == 'oldAddr'){
                this.form.birthAddr = this.currentAddr == ''? '北京市 北京市 东城区' : this.currentAddr;
            }else{
                this.form.nowAddr = this.currentAddr == ''? '北京市 北京市 东城区' : this.currentAddr;
            }
            this.addrShow = false;
        },
        // 获取地点
        getAddr(e){
            let arr = e.detail.values.map(vls =>{
                return vls.name
            })
            this.currentAddr = arr.join(' ')
        },

 
        // 打开弹出框显示出生日期
        openChooseBirth(type){
            this.type = type
            this.birthdayNewShow = true
        },

        // 关闭弹窗
        onClose(){
            this.birthdayNewShow = false;
            this.addrShow = false;
            this.relationShow = false;
        },
        // 获取选择的时间
        onInput(e){
            this.currentTime = e.detail;
        },
        // 获取性别
        changeSex(sex){
            this.form.sex = sex
        },
        // 获取昵称
        getNickname(e){
            console.log('e',e)
			let font = e.detail
			if(font.length == 6)
			{
				uni.showToast({
				    icon:'none',
				    title:'最多输入6个字！'
				})
			}
            this.form.nickName = font.slice(0,6);
        },

        // 上传头像
        uploadImg(){
            let _this= this;
            uni.showLoading({
                title: '上传中...'
            });
            uni.chooseImage({
                count: 1, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: async function (res) {
                        uni.uploadFile({
                        url: baseURL + '/sys/common/upload',
                        filePath: res.tempFilePaths[0],
                        header:{
                            'X-Access-Token':uni.getStorageSync("token") || ""
                        },
                        name: 'file',
                        success: (uploadFileRes) => {
                            console.log('uploadFileRes',JSON.parse(uploadFileRes.data))
                            const img = JSON.parse(uploadFileRes.data);
                            console.log('地址',baseURL+ '/'+img.message)
                            _this.form.avatar = baseURL+ '/'+img.message
                            _this.form.upAvatar = img.message
                            uni.hideLoading();
                        },
                        fail:(fail)=>{
                            console.log('fail',fail)
                        },
                    });
                    _this.form.avatar = res.tempFilePaths[0]
                }
            });

        }
    }
}
</script>
<style lang="less">

.relationBtn{
    width: 130rpx !important;
    height: 64rpx;
    line-height: 64rpx;
    text-align: center;
    background: #F8F8F9;
    border-radius: 4rpx;
    width: 48rpx;
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #222229;
}

.title{
    text-align: center; 
    margin-top: 30rpx;
}
.show{
    margin-bottom: 40rpx;
    margin-top: 40rpx; 
    display: flex; 
    justify-content: space-around; 
    color: #222229;
}
.boxWrap{
    height: 300rpx; 
    overflow: hidden;
}
.iptSyl{
    margin-top: 96rpx;
}
.sexWrap{
    display: flex;
    .sex{
        width: 158rpx;
        line-height: 44rpx;
        background: #F8F8F9;
        border-radius: 4rpx;
        text-align: center;
        color: #000;
        margin-left: 20rpx;
    }
}

.addImg{
    text-align: center;
    image{
        width: 128rpx;
        height: 128rpx;
        border-radius: 50%;
    }
    .avatar{
        font-size: 32rpx;
        margin-top: 24rpx;
    }
}

.wrap{
    padding: 0 30rpx;
}
.btn{
	margin: 30rpx 0;
    display: flex;
    justify-content: flex-end;
	button{
		width: 100% !important;
        line-height: 80rpx;
        min-height: 80rpx;
	}
}

</style>